<template>
<div>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="品牌名称" prop="brandName"
                :rules="[{required: true, message:'请输入品牌或者武器名称'}
                 ]">
              <el-input v-model="inputForm.brandName" placeholder="请填写品牌名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="厂家名称" prop="manufacturerId"
                :rules="[
                  {required: true, message:'请选择厂家', trigger:'change'}
                 ]">
              <el-select v-model="inputForm.manufacturerId" placeholder="请选择厂家" filterable clearable>
                <el-option
                  v-for="item in manufacturerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
           </el-form-item>
        </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          id: '',
          remarks: '',
          projectId: '',
          brandName: '',
          manufacturerId: ''
        },
        manufacturerList: []
      }
    },
    components: {
    },
    watch: {
      // 监听厂家列表变化，确保厂家名称正确显示
      manufacturerList: {
        handler(newVal) {
          if (newVal && newVal.length > 0 && this.inputForm.manufacturerId) {
            // 当厂家列表加载完成且有选中的厂家ID时，确保显示正确
            const manufacturer = newVal.find(item => item.id === this.inputForm.manufacturerId)
            if (manufacturer) {
              // 如果找到匹配的厂家，可以在这里做额外处理
              console.log('找到匹配的厂家:', manufacturer.name)
            }
          }
        },
        immediate: true
      }
    },
    methods: {
      // 数据恢复方法，用于处理后端返回的数据
      recover(target, source) {
        if (source && typeof source === 'object') {
          Object.keys(target).forEach(key => {
            if (source[key] !== undefined) {
              target[key] = source[key]
            }
          })
        }
        return target
      },
      // 获取厂家列表
      getManufacturerList() {
        this.$http({
          url: '/device/manufacturer/list',
          method: 'get'
        }).then(({data}) => {
          this.manufacturerList = data.page.list || []
        })
      },

      init (method, id) {
        this.method = method
        this.inputForm.id = id
        if (method === 'add') {
          this.title = `新建品牌`
        } else if (method === 'edit') {
          this.title = '修改品牌'
        } else if (method === 'view') {
          this.title = '查看品牌'
        }
        this.visible = true
        this.loading = false
        this.getManufacturerList()
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/device/deviceBrand/queryById`,
              method: 'get',
              params: { id: this.inputForm.id }
            }).then(({data}) => {
              if (data && data.success) {
                this.inputForm = this.recover(this.inputForm, data.deviceBrand)
                // 确保厂家ID正确设置
                if (this.inputForm.manufacturerId) {
                  // 确保厂家列表已加载
                  if (this.manufacturerList.length === 0) {
                    this.getManufacturerList()
                  }
                }
              }
            }).catch(() => {
              this.$message.error('数据加载失败')
            }).finally(() => {
              this.loading = false
            })
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/device/deviceBrand/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
              this.loading = false
            })
          }
        })
      }
    }
  }
</script>
